package com.cl.cloud.auth.config;

import com.cl.cloud.auth.exception.CustomWebResponseExceptionTranslator;
import lombok.SneakyThrows;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @description:
 * @author: liuzijian
 * @time: 2022-04-29 15:54
 */
@EnableWebSecurity// 默认开启，可以不写
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 加密方式 OAtuh2验证密码的方式是从数据库取密码 与
     * 前端传入的密码做一次加密之后与数据库密码（{@link com.cl.cloud.auth.service.CustomUserDetailsServiceImpl#loadUserByUsername}这个类返回的密码）做对比
     * 用到的是同一个PasswordEncoder
     * 所以{@link com.cl.cloud.auth.service.CustomUserDetailsServiceImpl#loadUserByUsername}这个类返回的密码需要用同一个加密对象进行加密
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }



    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);//如果自定义了AuthenticationManager则不需要调用该方法
        //auth.authenticationProvider()
    }

    /**
     * 与{@link CustomResourceServerConfiguration}中的配置不一样 这里配置的是spring security的
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().permitAll()
                .and().authorizeRequests()
                .antMatchers("/oauth/**").permitAll()
                .anyRequest().authenticated()
                .and().logout().permitAll()
                .and().cors().disable();
    }

    @Bean
    @Override
    @SneakyThrows
    public AuthenticationManager authenticationManagerBean() {
        return super.authenticationManagerBean();
    }



    @Bean
    public CustomWebResponseExceptionTranslator customWebResponseExceptionTranslator(){
        return new CustomWebResponseExceptionTranslator();
    }






}
